import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectorRef, Component, ElementRef, OnInit, Renderer2, ViewChild, ViewContainerRef} from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { CaseReviewService } from '../../../../../@core/service/case-review/case-review.service';
import { BizfileService } from '../../../../../@core/service/case-review/doc-service/api/bizfile.service';
import { DocsService } from '../../../../../@core/service/docs-service/docs-service.service';
import { StakeHolderService } from '../../../../../@core/service/handle-service/api/stakeHolder.service';

// 证据service
import { VgAPI, VgPlayer } from 'videogular2/compiled/core';
import { EvidenceService } from '../../../../../@core/service/evidence/api/evidence.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DomSanitizer } from '@angular/platform-browser';  
@Component({
  selector: 'app-steps',
  templateUrl: './steps.component.html',
  styleUrls: ['./steps.component.scss'],
  animations: [
    trigger('openClose', [
      state('open', style({
        height: '150px',
        opacity: 1,
      })),
      state('closed', style({
        height: '25px',
        opacity: 0.5,
      })),
      transition('open => closed', [
        animate('0.3s'),
      ]),
      transition('closed => open', [
        animate('0.3s'),
      ]),
    ]),
  ],
})
export class StepsComponent implements OnInit {

  constructor(
    public evidence: EvidenceService, // 证据service
    private bizfileService: BizfileService,
    private cdRef: ChangeDetectorRef,
    private active: ActivatedRoute,
    private stakeHolderService: StakeHolderService,
    private caseReview: CaseReviewService,
    private docsService: DocsService,
    private render2: Renderer2,
    private el: ElementRef,
    private message:NzMessageService,
    private sanitizer: DomSanitizer
  ) { }

  url:any = './audio@2x.png';

  public approveFlow: any[] = [];     // 文书流转
  bizfile :any = []                   // 文书列表
  bizfileListOther: any = [];         // 其他文书列表
  evidenceList: any = [];             // 证据列表
  cmsCaseInfo:any = {
    partyName:'',
    addressDetail:'',
    partyPhone:'',
    partyOtherPhone:''
  };                                 // 案件信息

  // 流程节点数据
  public processNodes = [
    {name: '线索', processName: '线索', value: 'clue', documentData: [], evidenceData: []},
    {name: '立案', processName: '立案', value: 'filing', documentData: [], evidenceData: []},
    {name: '调查取证', processName: '调查<br>取证', value: 'survey', documentData: [], evidenceData: []},
    {name: '处罚决定', processName: '处罚<br>决定', value: 'decide', documentData: [], evidenceData: []},
    {name: '执行与结案', processName: '执行<br>与结案', value: 'case', documentData: [], evidenceData: []},
    {name: '强制执行', processName: '强制<br>执行', value: 'measure', documentData: [], evidenceData: []},
  ];

  // 文件状态数据
  public fileStatus = {
    loading: '审批中',
    success: '审批完成',
    none: '',
  };
  public id:any;
  public sendMsg: object = {};
  isOpen = false;
  registerContent = '';     // 案件详情
  insertDate = '';          // 线索登记时间
  fileType = '';            // 文件类型
  loading = false;         // 数据加载动画
  type = '';                // 路由参数 区分从案件处理还是案件审批中进入
  oprea: string;                    // 路由参数 区分是查看还是审批或办理的操作
  registUerName = '';       // 登记人员名称
  caseUserName: string[];           // 办案人员名称
  paramId: string[];               // 案件id
  isExpand :boolean;        // card
  api: VgAPI;

  // 证据查看
    public publictypeFlag = ''; // 判断显示音视频
    public fileId: any = null; // 证据的文件ID
    public isVisible = false; // 证据查看

  ngOnInit() {
    this.paramId = this.active.snapshot.params['id'];
    this.oprea = this.active.snapshot.params['opera'];
    this.type = this.active.snapshot.params['type'];
    this.getFileList(this.paramId);
    this.getEvidenceList(this.paramId);
    this.sendMsg['id'] = this.paramId;
    this.sendMsg['type'] = this.type;
  
    if (this.active.snapshot.params['id']) {
      this.id = this.active.snapshot.params['id'];
    }
  }

  // 左侧根据文书状态匹配steps颜色 如果当前文书列表和证据列表都为空 primary 否则为 success 且审批状态如果为‘待审批’为 danger
  badge(item): string {
    if(item){ 
      if(item.documentData){
        if (item.documentData.length <= 0 && item.evidenceData.length <= 0) {
          return 'primary';
        } else {
          if (item.documentData.length > 0) {
            if (item.documentData.filter((item) => item.approveStatus === '待审批').length > 0) {
              return 'danger';
            } else {
              return 'success';
            }
          } else if (item.evidenceData.length > 0) {
            if (item.evidenceData.filter((item) => item.approveStatus === '待审批').length > 0) {
              return 'danger';
            } else {
              return 'success';
            }
          }
        }
      }else{
        if(item.docSource == '三方系统'){
          return 'success'
        }
      }
    }else{
      return 'primary'
    }
  }

  // 根据匹配审批待审批状态
  badgeApprove(approveStatus : string){
    if (approveStatus === '已审批') {
      return 'badge-done';
    } else {
      return 'badge-success';
    }
  }

    // 获取文件列表
  getFileList(paramId) {
    this.bizfileService.queryDocByPage(paramId, 0, 100).subscribe((res) => {
      if (res['code'] === 4) {
        const list = res['data']['data'];
        this.bizfile = list.filter((item) => item.doctype !== '其他');
        this.bizfileListOther = list.filter((item) => item.doctype === '其他');

        this.clearFileList();
        if (list.length > 0) {
          this.judgeLink(list, 'documentData');
        }
        // this.calcTerminalHeight();
      }
      this.cdRef.detectChanges();
      this.getUsersInfo(paramId);
    }, (error) => {
    });
  }
  // 获取证据列表
  getEvidenceList(paramId) {
    this.evidence.evidenceObjectIdObjectIdGet(paramId).subscribe((data: any) => {
      const evidenceList = data.data;
      this.evidenceList = data.data;
      this.clearEvidenceList();
      if (evidenceList.length > 0) {
        this.judgeLink(evidenceList, 'evidenceData');
      }
    });
  }

    // 每次更新刷新文书列表
    clearFileList() {
      this.processNodes.forEach(item => {
        item.documentData = []
      });
    }
    // 每次更新刷新证据列表
    clearEvidenceList() {
      this.processNodes.forEach(item => {
        item.evidenceData = []
      });
    }

    // 刷新文书 & 证据
    onRefinsh({ name }) {
      if (name === 'bizfile') {
        this.getFileList(this.paramId);
      } else {
        this.getEvidenceList(this.paramId);
      }
    }

  // 判断流程环节获取数据
  judgeLink(data, dataItemName) {
    if (!data) { return ; }
    for (let i = 0; i < data.length; i++) {
      switch (data[i]['stage'] || data[i]['filingLink']) {
        case '线索核查':
        case '线索': {
          this.filterData('线索', dataItemName, data[i]);
        }          break;
        case '立案': {
          this.filterData('立案', dataItemName, data[i]);
        }          break;
        case '调查取证': {
          this.filterData('调查取证', dataItemName, data[i]);
        }            break;
        case '处罚决定': {
          this.filterData('处罚决定', dataItemName, data[i]);
        }            break;
        case '执行与结案': {
          this.filterData('执行与结案', dataItemName, data[i]);
        }             break;
        case '强制执行': {
          this.filterData('强制执行', dataItemName, data[i]);
        }            break;
      }
      if (dataItemName === 'documentData' && data[i]['doctype'] === '案件来源登记表') {
        this.registerContent = JSON.parse(data[i]['formJson'])['registerContent'];
        this.insertDate = data[i]['insertDate'];
      }
    }
  }

  // 筛选数据
  filterData(name, dataItemName, data) {
    if (!data || !name || !dataItemName) { return ; }
    for (let j = 0; j < this.processNodes.length; j++) {
      if (this.processNodes[j]['name'] === name) {
        this.processNodes[j][dataItemName].push(data);
      }
    }
  }

  onPlayerReady(api: VgAPI) {
    this.api = api;
    this.api.getDefaultMedia().subscriptions.ended.subscribe(
      () => {
        // Set the video to the beginning
        this.api.getDefaultMedia().currentTime = 0;
      },
    );
  }

  public typeFlag:boolean = false;

  showModal(contentType, fileId, condition): void {
    this.isVisible = true;
    this.fileId = fileId;
    this.publictypeFlag  = contentType;
   // 证据查看
    if (condition === 'evidence') {
        this.evidence.evidenceFileIdGet(fileId).subscribe((res:any)=>{
          this.afterLoadMedia(res);
      },(error)=>{
        this.message.create('error','证据查询失败！')
        this.handleCancel();
      })

    // 文书查看  
    } else if (condition === 'bizfile') {
        this.bizfileService.downloadFile(fileId).subscribe((res:any) => {
          this.afterLoadMedia(res);
        }, (error) => { 
          this.message.create('error','文书查询失败！')
          this.handleCancel();
        });
    // 终端数据查看    
    } 
    
    if (contentType.includes('image') || contentType.includes('pdf')) {
      // this.typeFlag = true;
      // const img = new Image();
      // img.src = this.url;
      // img.onload = () => {
      //   this.typeFlag = false;
      // };
    } else if (contentType.includes('audio')) {

    } else if (contentType.includes('video')) {

    }
  }

  // 音频视频加载后set操作
  afterLoadMedia(res){
    let url = URL.createObjectURL(res)
    this.url =  this.sanitizer.bypassSecurityTrustResourceUrl(url); 
    this.typeFlag = true;
  }


  handleOk(): void {
    this.isVisible = false;
  }
  handleCancel(): void {
    this.isVisible = false;
    this.loading = false;
    this.publictypeFlag = '';
    this.typeFlag = false;
  }

  // 获取办案人 登记人信息
  getUsersInfo(paramId) {
    this.stakeHolderService.stakeHolderCaseIdCaseIdGet(paramId).subscribe((res) => {
      if (res['rel'] === true) {
        this.registUerName = res['data']['cmsCaseInfo']['registrant']['registerName'] || '';
        this.cmsCaseInfo = res['data']['cmsCaseInfo'];
        this.caseUserName = [];
        for (let i = 0; i < res['data']['caseHandlerInfo'].length; i++) {
          this.caseUserName.push(res['data']['caseHandlerInfo'][i]['userName']);
        }
      }

    }, (error) => {
    });
  }

  // 文字信息展开与收起
  toggle() {
    this.isOpen = !this.isOpen;
  }

  // 流程点击事件
  move(el) {
    const ele = this.el.nativeElement.querySelector(`.${el}`);
    if (ele) {
      ele.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
    }
  }

  // 查询文件
  queryDocByPage(id) {
    this.bizfileService.queryDocByPage(id, 1, 100).subscribe((data) => {
      this.getFileList(this.paramId)
    });

  }

  // 查看
  view(docid, doctype) {
    this.caseReview.setShowWindow(true);
    this.caseReview.getCreateCaseDoc().emit({condition: 'See', docid, doctype, bizid: this.paramId, callback: this.queryDocByPage.bind(this)});
  }

  // 下载文件
  download(fileid,fileName,downloadText) {
    if(downloadText === 'bizfile'){
      this.bizfileService.downloadFile(fileid).subscribe((res:any) => {
        this.createA2Click(res,fileName)
      }, (error) => { 
        this.message.create('error','文书下载失败！')
      });
    }else if(downloadText === 'evidence'){
      this.evidence.evidenceFileIdGet(fileid).subscribe((res:any)=>{
          this.createA2Click(res,fileName)
      },(error)=>{
        this.message.create('error','证据下载失败！')
      })
    }
  }

  createA2Click(res,fileName){
    const fileURL = URL.createObjectURL(res);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = fileName;
    a.href = fileURL;
    a.click();
  }

  // 获取文件流程
  getApproveFlow(id) {
    if (!id && id === undefined) { return ; }
    if (this.docsService.get(id)) {
      this.approveFlow = this.docsService.get(id);
    } else {
      this.queryApproveFlow(id);
    }
  }

  // 通过文件ID查询文件流程
  queryApproveFlow(id) {
    this.bizfileService.queryApproveFlow(id).subscribe( (data) => {
      if (data['code'] === 4) {
        this.approveFlow = data['data'];
        this.docsService.set(id, this.approveFlow);
      }
    }, (error) => {

    });
  }

 // 审批事件
 approval(docid, doctype): void {
  this.caseReview.setShowWindow(true);
  this.caseReview.getCreateCaseDoc().emit({condition: 'Approval', docid, doctype, bizid: this.id, callback: ()=>{
    this.getFileList(this.paramId);
    this.approveReload(docid);
  }});
}
  // 刷新文件流程
  approveReload(id) {
    this.queryApproveFlow(id);
  }

    // 底部卡片展开与收起
    cardToggle() {
      // this.isExpand = !this.isExpand;
      // this.expandAnimation.emit(this.isExpand);
    }
}
